package com.hys.ultrasound.business.activity;

import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.SPUtils;
import com.hys.ultrasound.R;
import com.hys.ultrasound.base.ui.BaseActivity;
import com.hys.ultrasound.business.login.LoginPresenter;
import com.hys.ultrasound.business.login.LoginView;
import com.hys.ultrasound.data.entity.AppVersion;
import com.hys.ultrasound.data.entity.UserInfo;
import com.hys.ultrasound.utils.DownloadFileUtil;
import com.lpjeremy.libmodule.http.exception.ApiException;

import butterknife.BindView;

/**
 * @desc:启动+登录页
 * @date:2019/4/17 15:19
 * @auther:lp
 * @version:1.1.6
 */
public class WelcomeActivity extends BaseActivity implements LoginView, View.OnClickListener, DownloadFileUtil.DownloadListener {
    @BindView(R.id.edtAccount)
    EditText mEdtAccount;
    @BindView(R.id.edtPwd)
    EditText mEdtPwd;
    @BindView(R.id.btnLogin)
    Button mBtnLogin;
    @BindView(R.id.layoutLogin)
    LinearLayout mLayoutLogin;
    @BindView(R.id.txtContent)
    TextView mTxtContent;
    @BindView(R.id.btnNoUpgrade)
    TextView mBtnNoUpgrade;
    @BindView(R.id.btnUpgrade)
    TextView mBtnUpgrade;
    @BindView(R.id.layoutUpgrade)
    LinearLayout mLayoutUpgrade;
    @BindView(R.id.layoutUpgradeContent)
    LinearLayout mLayoutUpgradeContent;
    @BindView(R.id.layoutBtn)
    LinearLayout mLayoutBtn;
    @BindView(R.id.txtProgress)
    TextView mTxtProgress;
    @BindView(R.id.layoutProgress)
    LinearLayout mLayoutProgress;

    private LoginPresenter mLoginPresenter;

    private AppVersion appVersion;

    private String saveApkPath;

    @Override
    protected void initView() {
        getSaveApkPath();

        mLoginPresenter = new LoginPresenter();
        mLoginPresenter.attachView(this);
        //检测升级
//        mLoginPresenter.checkAppVersion();

        mBtnLogin.setOnClickListener(this);
        mBtnNoUpgrade.setOnClickListener(this);
        mBtnUpgrade.setOnClickListener(this);

        mEdtPwd.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEND || actionId == EditorInfo.IME_ACTION_DONE || (event != null && KeyEvent.KEYCODE_ENTER == event.getKeyCode() && KeyEvent.ACTION_DOWN == event.getAction())) {
                    tryLogin();
                }
                return false;
            }
        });

    }

    @Override
    protected void initData() {
        String uName = SPUtils.getInstance().getString("scanUserName");
        String pwd = SPUtils.getInstance().getString("scanUserPwd");
        if (!TextUtils.isEmpty(uName))
            mEdtAccount.setText(uName);
        if (!TextUtils.isEmpty(pwd))
            mEdtPwd.setText(pwd);
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_login;
    }

    @Override
    public void onLoginSuccess(UserInfo userInfo) {
        startActivity(MainActivity.class);
        finish();
    }

    @Override
    public void onLoginFail(ApiException e) {
        showToast(e.getMessage());
        if (mLayoutLogin.getVisibility() == View.GONE) {
            mLayoutLogin.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void checkAppVersionSuccess(AppVersion appVersion) {
        if (appVersion != null) {
            this.appVersion = appVersion;
            mLayoutUpgrade.setVisibility(View.VISIBLE);
            mTxtContent.setText(TextUtils.isEmpty(appVersion.getUpgradeContent()) ? "有最新版本，请立刻升级！" : appVersion.getUpgradeContent());
        } else {
            tryLogin();
        }
    }

    @Override
    public void checkAppVersionFail(ApiException e) {
        tryLogin();
    }

    private void tryLogin() {
        String uName = mEdtAccount.getText().toString().trim();
        String pwd = mEdtPwd.getText().toString().trim();

        if (!TextUtils.isEmpty(uName) && !TextUtils.isEmpty(pwd)) {
            mLoginPresenter.login(uName, pwd);
        } else {
            mLayoutLogin.setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mLoginPresenter != null) {
            mLoginPresenter.detachView();
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btnLogin:
//                mLoginPresenter.login(mEdtAccount.getText().toString().trim(), mEdtPwd.getText().toString().trim());
                onLoginSuccess(null);
                break;
            case R.id.btnNoUpgrade:
                mLayoutUpgrade.setVisibility(View.GONE);
                tryLogin();
                break;
            case R.id.btnUpgrade:
                if (appVersion != null) {
                    mLayoutBtn.setVisibility(View.GONE);
                    mLayoutProgress.setVisibility(View.VISIBLE);
                    mTxtProgress.setText("0%");
                    DownloadFileUtil.downloadFile(appVersion.getDownloadUrl(), this, getSaveApkPath());
                }
                break;
        }
    }

    public String getSaveApkPath() {
        if (TextUtils.isEmpty(saveApkPath)) {
            saveApkPath = mContext.getExternalCacheDir().getAbsolutePath() + "/ultrasound.apk";
        }
        return saveApkPath;
    }

    @Override
    public void downloadProgress(final long total, final long progress) {
        final int per = (int) (progress * 100 / total);
        post(new Runnable() {
            @Override
            public void run() {
                mTxtProgress.setText(per + "%");
                if (progress == total) {
                    //下载完成，安装
                    AppUtils.installApp(saveApkPath);
                    if (mApplication != null) {
                        mApplication.exitApp(mContext);
                    } else {
                        finish();
                    }
                }
            }
        });

    }

    @Override
    public void downloadFail() {
        showToast("升级失败，请重试！");
        post(new Runnable() {
            @Override
            public void run() {
                mLayoutProgress.setVisibility(View.GONE);
                mLayoutBtn.setVisibility(View.VISIBLE);
            }
        });

    }
}
